package data

import (
	"encoding/json"
	"land/config"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
)

func SelectHandler(w http.ResponseWriter, r *http.Request) {

	config.AllowCors(w)

	// 解析表单数据
	if err := r.ParseMultipartForm(10 << 20); err != nil { // 设置最大上传文件大小为10MB
		http.Error(w, "无法解析表单", http.StatusBadRequest)
		log.Printf("解析表单数据时出错: %v", err)
		return
	}
	// log.Println("表单数据:", r.Form)

	// 从表单数据中获取用户信息
	userID := r.FormValue("id")
	// log.Println("用户ID:", userID)

	// 转换用户ID为整数
	id, err := strconv.ParseUint(userID, 10, 32)
	if err != nil {
		http.Error(w, "无效的用户ID", http.StatusBadRequest)
		return
	}
	// log.Println("用户ID(整数):", id)

	// 指定用户文件夹
	userFolder := filepath.Join(config.SaveFolderName, strconv.Itoa(int(id)))
	healthReportFolder := filepath.Join(userFolder, config.HealthReportFolderName)

	// log.Printf("用户文件夹: %s", userFolder)
	// log.Printf("健康报告文件夹: %s", healthReportFolder)

	// 检查健康报告文件夹是否存在
	if _, err := os.Stat(healthReportFolder); os.IsNotExist(err) {
		http.Error(w, `{"error": "健康报告文件夹未找到"}`, http.StatusNotFound)
		return
	}

	// 获取健康报告文件夹下的所有健康报告文件名
	var healthReportNames []string
	err = filepath.Walk(healthReportFolder, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		// 检查是否是文件并且文件名以 .pdf 结尾
		if !info.IsDir() && filepath.Ext(info.Name()) == ".pdf" {
			healthReportNames = append(healthReportNames, info.Name())
		}
		return nil
	})
	if err != nil {
		http.Error(w, "无法读取健康报告文件夹", http.StatusInternalServerError)
		return
	}
	// log.Printf("健康报告文件名: %v", healthReportNames)

	// 设置响应头，返回健康报告文件名给前端
	w.Header().Set("Content-Type", "application/json")

	response := map[string]interface{}{
		"health_reports": healthReportNames,
	}

	// 设置响应头
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")

	// 返回JSON响应
	json.NewEncoder(w).Encode(response)
	// log.Printf("健康报告文件名响应: %v", response)
}
